package com.jy.admin.jobs;

import com.fqgj.common.api.Page;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jy.admin.config.ApolloConfigUtil;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.enums.SendTaskStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2021/11/28
 * Time: 10:28 下午
 */
@Service
public class SendSmsExpandJob {

    private static final Logger LOGGER = LoggerFactory.getLogger(SendSmsExpandJob.class);

    @Autowired
    private OpdCsvExpandDao opdCsvExpandDao;

    @Autowired
    private SmsSendTaskDao smsSendTaskDao;

    @Autowired
    private SmsSendChannelDao smsSendChannelDao;

    @Autowired
    private SmsTemplateDao smsTemplateDao;

    @Autowired
    private SmsSendLogDao smsSendLogDao;

    @Autowired
    private ApolloConfigUtil configUtil;


//    @Scheduled(fixedDelay = 1000L * 20)
    public void run() {

        LOGGER.info("== sms-send-pre start sending sms ==");
        List<SmsSendTaskEntity> watingList = smsSendTaskDao.getListByStatus(SendTaskStatusEnum.Waiting.getStatus());
        if (CollectionUtils.isEmpty(watingList)) {
            LOGGER.info("==sms-send-pre  start sending sms  ==,size=0");
            return;
        }

        LOGGER.info("==sms-send-pre  start sending sms ==,size:{}", watingList.size());

        watingList.forEach(smsSendTaskEntity -> {
            SmsSendChannelEntity channelEntity = smsSendChannelDao.getByChannelCode(smsSendTaskEntity.getChannleCode());
            SmsTemplateEntity templateEntity = smsTemplateDao.getByTemplateNo(smsSendTaskEntity.getTemplateNo());
            if (channelEntity == null || templateEntity == null) {
                smsSendTaskEntity.setStatus(SendTaskStatusEnum.Exception.getStatus());
                smsSendTaskDao.updateByPrimaryKey(smsSendTaskEntity);
                LOGGER.error("==sms-send-pre  start sending sms ==,channelEntity || templateEntity is null,taskNo:{}", smsSendTaskEntity.getTaskNo());
                return;
            }

//            String finalContent = getFinalContent(templateEntity.getContent(), JsonIterator.deserialize(smsSendTaskEntity.getParams()).asMap());

            LOGGER.info("==sms-send-pre  start sending sms ==,taskNo:{}", smsSendTaskEntity.getTaskNo());


            int pageSize = 1000;
            int currentPage = 1;
            Page page1 = new Page();
            page1.setCurrentPage(currentPage);
            page1.setPageSize(pageSize);

            while (true) {
                List<OpdCsvExpandEntity> listByDataNo = opdCsvExpandDao.getListByDataNoAndDndStatus(smsSendTaskEntity.getDataNo(), 0, page1);
                if (CollectionUtils.isEmpty(listByDataNo)) {
                    LOGGER.info("===sms-send-pre  listByDataNo size ==0 ==");
                    smsSendTaskEntity.setStatus(SendTaskStatusEnum.create_pre_success.getStatus());
                    smsSendTaskDao.updateByPrimaryKey(smsSendTaskEntity);
                    return;
                }
                LOGGER.info("===sms-send-pre  listByDataNo size:{} ==", listByDataNo.size());

                List<String> allMobiles = new ArrayList<>();
                listByDataNo.forEach(opdCsvExpandEntity -> {
                    if (StringUtils.isEmpty(opdCsvExpandEntity.getMobile())) {
                        return;
                    }
                    LOGGER.info("===sms-send-pre  mobile detail  ==,dataNo:{},mobile:{}", opdCsvExpandEntity.getDataNo(), opdCsvExpandEntity.getMobile());
                    allMobiles.add(opdCsvExpandEntity.getMobile());
                });

                if (CollectionUtils.isEmpty(allMobiles)) {
                    continue;
                }
                try {

                    //发送短信

                    createPreSendLog(smsSendTaskEntity.getId(), smsSendTaskEntity.getTaskNo(), smsSendTaskEntity.getProvider(), allMobiles, smsSendTaskEntity.getParams(), templateEntity, channelEntity, smsSendTaskEntity.getJumpUrl(), page1.getStartIndex());

                    if (listByDataNo.size() < pageSize) {
                        smsSendTaskEntity.setStatus(SendTaskStatusEnum.create_pre_success.getStatus());
                        smsSendTaskDao.updateByPrimaryKey(smsSendTaskEntity);
                        break;
                    }

                    currentPage++;
                    page1.setCurrentPage(currentPage);
                } catch (Exception e) {
                    LOGGER.error("==sms-send-pre  get dndMobileList error ==", e);
                }
            }
        });
    }


    private void createPreSendLog(Long taskId, String taskNo, String provider, List<String> mobiles, String params, SmsTemplateEntity template, SmsSendChannelEntity channel, String targetUrl, int start) {

        String contentTemplate = template.getContent();
        Map<String, Any> stringAnyMap = JsonIterator.deserialize(params).asMap();
        Map<String, String> res = new HashMap<>();
        stringAnyMap.forEach((s, any) -> {
            res.put(s, any.toString());
        });

        int i = 0;
        for (String mobile : mobiles) {
            i++;
            String tag = numberToLetter(taskId) + "1" + numberToLetter(start + i);
            LOGGER.info("== numberToLetter ==,a:{},b:{}", taskId , start + i);
            if (stringAnyMap.containsKey("##url##")) {
                res.put("##url##", configUtil.getShotLinkPre() + tag);
            }

            String finalContent = getFinalContent(contentTemplate, res);
            SmsSendLogEntity smsSendLogEntity = new SmsSendLogEntity()
                    .setProvider(provider)
                    .setContent(finalContent)
                    .setMobile(mobile)
                    .setTaskNo(taskNo)
                    .setSendDt(new Date())
                    .setFee(channel.getFee())
                    .setTag(tag)
                    .setJumpUrl(targetUrl);

            smsSendLogDao.insert(smsSendLogEntity);
        }


    }


    private String getFinalContent(String contentTemplate, Map<String, String> replaceValues) {


        for (String key : replaceValues.keySet()) {
            contentTemplate = contentTemplate.replace(key, replaceValues.get(key));
        }

        LOGGER.info("==sms-send-pre==,send content:{}", contentTemplate);

        return contentTemplate;

    }

    public static void main(String[] args) {
        String s = numberToLetter(5);
        System.err.println(numberToLetter(50000));
        System.err.println(numberToLetter(100000));
    }

    private static final String BASE = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

    public static String toBase62(long num) {
        StringBuilder sb = new StringBuilder();
        do {
            int i = (int) (num % 62);
            sb.append(BASE.charAt(i));
            num /= 62;
        } while (num > 0);

        return sb.reverse().toString();
    }

    private static String numberToLetter(long num) {
        if (num <= 0) {
            return null;
        }
        String letter = "";
        num--;
        do {
            if (letter.length() > 0) {
                num--;
            }
            long l = num % 26;
            letter = ((char) (l + (int) 'A')) + letter;
            num = (int) ((num - l) / 26);
        } while (num > 0);

        return letter;
    }
}
